/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */
package com.ykht.proj.coupon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codingapi.tx.annotation.TxTransaction;
import com.ykht.proj.admin.api.Enum.UserRoleTypeEnum;
import com.ykht.proj.admin.api.dto.UserDTO;
import com.ykht.proj.admin.api.entity.SysUser;
import com.ykht.proj.admin.api.feign.RemoteFileService;
import com.ykht.proj.admin.api.feign.RemoteUserService;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.UserTypeEnum;
import com.ykht.proj.coupon.dto.UserExtDto;
import com.ykht.proj.coupon.entity.CnCompany;
import com.ykht.proj.coupon.mapper.CnCompanyMapper;
import com.ykht.proj.coupon.service.CnCompanyService;
import com.ykht.proj.coupon.vo.CnBrandVo;
import com.ykht.proj.coupon.vo.CnCompanyVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 公司表
 *
 * @author proj code generator
 * @date 2020-11-17 14:05:06
 */
@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class CnCompanyServiceImpl extends ServiceImpl<CnCompanyMapper, CnCompany> implements CnCompanyService {

	private final RemoteFileService fileService;

	private final CnCompanyMapper cnCompanyMapper;

	private final RemoteUserService remoteUserService;

	@Value("${oss.baseHost}")
	private String ossBaseHost;

	@Override
	public Map uploadFile(MultipartFile file) {
		R upload = fileService.upload(file);
		Map<String, String> resultMap = (Map<String, String>) upload.getData();
		String fileName = ossBaseHost + resultMap.get("fileName");
		log.info("上传文件地址为：{}", fileName);
		resultMap.put("fileName", fileName);
		return resultMap;
	}

	/**
	 * 根据角色类型 获取后台的公司列表 分页查询
	 *
	 * @param page
	 * @param cnCompany
	 * @return
	 */
	@Override
	public IPage<CnCompanyVo> getCnCompanyPage(Page page, CnCompany cnCompany) {
		Integer userType = SecurityUtils.getUser().getUserType();
		if (userType.equals(UserTypeEnum.company.getValue())) {
			cnCompany.setLoginId(SecurityUtils.getUserId());
		}
		IPage<CnCompanyVo> cnCompanyVoIPage = cnCompanyMapper.getCnCompanyPage(page, cnCompany);
		List<CnCompanyVo> list = cnCompanyVoIPage.getRecords();
		if (list != null && list.size() > 0) {
			List<Long> loginList = list.stream().map(CnCompanyVo::getLoginId).collect(Collectors.toList());
			List<SysUser> userList = remoteUserService.userByIds(loginList);
			list.stream().forEach(itme -> {
				userList.stream().forEach(user -> {
					if (Long.valueOf(user.getUserId()).equals(itme.getLoginId())) {
						itme.setUsername(user.getUsername());
					}
				});
			});
		}
		return cnCompanyVoIPage;
	}

	/**
	 * 新增公司表
	 *
	 * @param cnCompanyVo
	 */
	@TxTransaction(isStart = true) // 请求方 要加 isStart = true  被请求的不用加  isStart = true  控制事物 注解
	@Transactional(rollbackFor = Exception.class)
	@Override
	public R saveAndUser(CnCompanyVo cnCompanyVo) throws Exception {
		CnCompany company = new CnCompany().selectOne(Wrappers.lambdaQuery(CnCompany.class).eq(CnCompany::getName, cnCompanyVo.getName()));
		if (company != null) {
			return R.ok("公司名称已经存在");
		}
		if (cnCompanyVo.getDisplay().equals(0)) {
			if (cnCompanyVo.getContractStartTime().isAfter(LocalDateTime.now()) || cnCompanyVo.getContractEndTime().isBefore(LocalDateTime.now())) {
				return R.failed("当前时间不在该公司合作时间内，不能上架");
			}
			cnCompanyVo.setOnTime(LocalDateTime.now());
		} else {
			cnCompanyVo.setOffTime(LocalDateTime.now());
		}
		cnCompanyVo.setCreateTime(LocalDateTime.now());
		cnCompanyVo.setCreateUser(SecurityUtils.getUserId());
		cnCompanyVo.setUserType(UserTypeEnum.company.getValue());
		CnCompany cnCompany = BeanUtil.toBean(cnCompanyVo, CnCompany.class);
		cnCompanyMapper.insert(cnCompany);
		cnCompanyVo.setId(cnCompany.getId());
		if (cnCompany.getLoginId() != null) {
			SysUser user = new SysUser();
			user.setUserId(Integer.parseInt(cnCompany.getLoginId().toString()));
			user.setSjIdDefLogin(cnCompany.getId());
			R bindSj = remoteUserService.bindSj(user);
		}
		if (cnCompanyVo.getLoginId() == null) {
			UserDTO userDTO = new UserDTO();
			userDTO.setUsername(StringUtils.isEmpty(cnCompanyVo.getUsername()) ? cnCompany.getName() : cnCompanyVo.getUsername());
			userDTO.setUserType(UserTypeEnum.company.getValue());
			userDTO.setPassword("123456");
			userDTO.setParentId(cnCompanyVo.getParentId());
			userDTO.setRole(UserRoleTypeEnum.company.getValue());
			userDTO.setSjIdDefLogin(cnCompany.getId());
			R<UserDTO> userDTOR = remoteUserService.saveUser(userDTO);
			if (userDTOR.getCode() != 0) {
				throw new RuntimeException(userDTOR.getMsg());
			}
			cnCompany.setLoginId(Long.valueOf(userDTOR.getData().getUserId()));
			this.updateById(cnCompany);
		}
		return R.ok(cnCompanyVo);
	}

	/**
	 * 修改公司表
	 *
	 * @param cnCompanyVo
	 * @return
	 */
	@TxTransaction(isStart = true) // 请求方 要加 isStart = true  被请求的不用加  isStart = true  控制事物 注解
	@Transactional(rollbackFor = Exception.class)
	@Override
	public R updateAndUser(CnCompanyVo cnCompanyVo) throws Exception {
		CnCompany company = new CnCompany().selectOne(Wrappers.lambdaQuery(CnCompany.class)
				.eq(CnCompany::getName, cnCompanyVo.getName())
				.ne(CnCompany::getId, cnCompanyVo.getId()));
		if (company != null) {
			return R.ok("公司名称已经存在");
		}
		cnCompanyVo.setUpdateUser(SecurityUtils.getUserId());
		cnCompanyVo.setUpdateTime(LocalDateTime.now());
		cnCompanyVo.setUserType(UserTypeEnum.company.getValue());
		if (cnCompanyVo.getLoginId() != null) {
			SysUser user = new SysUser();
			user.setUserId(Integer.parseInt(cnCompanyVo.getLoginId().toString()));
			user.setSjIdDefLogin(cnCompanyVo.getId());
			remoteUserService.bindSj(user);
		}
		if (null != cnCompanyVo.getUsername()) {
			UserDTO userDTO = new UserDTO();
			userDTO.setUsername(cnCompanyVo.getUsername());
			userDTO.setUserType(UserTypeEnum.company.getValue());
			userDTO.setPassword("123456");
			userDTO.setParentId(cnCompanyVo.getParentId());
			userDTO.setRole(UserRoleTypeEnum.company.getValue());
			userDTO.setSjIdDefLogin(cnCompanyVo.getId());
			R<UserDTO> userDTOR = remoteUserService.saveUser(userDTO);
			if (userDTOR.getCode() != 0) {
				throw new RuntimeException(userDTOR.getMsg());
			}
			cnCompanyVo.setLoginId(Long.valueOf(userDTOR.getData().getUserId()));
		}
		CnCompany cnCompany = BeanUtil.toBean(cnCompanyVo, CnCompany.class);
		cnCompanyMapper.updateById(cnCompany);
		return R.ok(cnCompanyVo);
	}

	/**
	 * 公司上下架
	 *
	 * @param cnCompanyVo
	 * @return
	 */
	@Override
	public R updateByDisplay(CnCompanyVo cnCompanyVo) throws Exception {
		cnCompanyVo.setUpdateUser(SecurityUtils.getUserId());
		cnCompanyVo.setUpdateTime(LocalDateTime.now());
		CnCompany company = BeanUtil.toBean(cnCompanyVo, CnCompany.class);
		// 上架
		if (cnCompanyVo.getDisplay().equals(0)) {
			CnCompany cnCompany = this.getById(cnCompanyVo.getId());
			if (cnCompany.getContractStartTime().isAfter(LocalDateTime.now()) || cnCompany.getContractEndTime().isBefore(LocalDateTime.now())) {
				return R.failed("当前时间不在该公司合作时间内，不能上架");
			}
			company.setOnTime(LocalDateTime.now());
			return R.ok(this.updateById(company));
			// 下架
		} else {
			company.setOffTime(LocalDateTime.now());

			return R.ok();
		}
	}
}
